package org.example.impl;

import org.example.pojo.clientInfo;
import org.example.tools.utilsTools;

import java.net.Socket;
import java.util.*;

/**
 * @see clientSelectDataMapsImpl Map中内消息匹配
 */
public class clientSelectDataMapsImpl{
    private final Map.Entry<Socket, clientInfo> socketClientInfoEntry;
    private final byte[] Userdata;

    public clientSelectDataMapsImpl(Map.Entry<Socket, clientInfo> socketClientInfoEntry,byte[] dat) {
        this.socketClientInfoEntry = socketClientInfoEntry;
        this.Userdata = dat;
    }
    /**
     * 外层
     */
    public void startSelect() {
        synchronized (this){
            try {
                switch (socketClientInfoEntry.getValue().getIsDbClient()){
                    case 0:zeroController();break;
                    case 1:oneController();break;
                    default:exitSocket(socketClientInfoEntry.getKey());break;
                }
            }catch (Exception e){e.printStackTrace();}
        }
    }
    private void zeroController(){
        Set<Map.Entry<Socket, clientInfo>> socketMap = utilsTools.UserMaps.entrySet();
        isInstruction();
        for (Map.Entry<Socket,clientInfo> zero:socketMap){
            // 0进入后要判断 不是自身 而且还必须是1
            if(!socketClientInfoEntry.getKey().equals(zero.getKey())){
                if(zero.getValue().getIsDbClient()==1){
                    oneAndZeroController(zero.getValue().getGroup(),zero.getKey());
                }
            }
        }
    }
    private void oneController(){
        try {
            Set<Map.Entry<Socket, clientInfo>> socketMap = utilsTools.UserMaps.entrySet();
            for (Map.Entry<Socket,clientInfo> one:socketMap){
                // 1进入后要判断 不是自身 而且还必须是0    否则如果是自身  处理权限
                if(!socketClientInfoEntry.getKey().equals(one.getKey())){
                    //寻找 0 进行消息发送
                    if(one.getValue().getIsDbClient()==0){
                        oneInstructionController(one.getValue().getGroup(),one.getKey());
                        oneForwardingZeroMessagesController(one.getValue().getGroup(),one.getKey());
                    }
                }
            }
        }catch (Exception e){e.printStackTrace();}
    }
    private void exitSocket(Socket socket){
        try {
            socket.getOutputStream().write("非法权限强制关闭".getBytes());
            socket.close();
            utilsTools.UserMaps.remove(socket);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void oneAndZeroController(List<String> groups,Socket socket){
        for (String UserGroup:socketClientInfoEntry.getValue().getGroup()){
            for (String zeroGroups : groups){
                if(UserGroup.equals(zeroGroups)){
                    JudgeInstruction(socket);
                }
            }
        }
    }
    //1 消息转发给相同组的 0 客户端
    private void oneForwardingZeroMessagesController(List<String> groups,Socket socket){
        for (String UserGroup:socketClientInfoEntry.getValue().getGroup()){
            for (String zeroGroups : groups){
                if(UserGroup.equals(zeroGroups)){
                    JudgeInstruction(socket);
                }
            }
        }
    }

    //  判断是否为指令语句
    private void JudgeInstruction(Socket socket){
        try {
            String data = new String(Userdata);
            if(!"".equals(data)){
                boolean bl = !data.contains("<dbClient>") && !data.contains("<group>") && !data.contains("<get>") && !data.contains("<up>") && !data.contains("<removes>") && !data.contains("<del>") && !data.contains("<send>") && !data.contains("<values>");
                if(bl){
                    socket.getOutputStream().write(Userdata);
                }
            }
        }catch (Exception e){e.printStackTrace();}
    }


    // 1 拥有权限指令控制
    private void oneInstructionController(List<String> groups,Socket socket){
        try {
            if(socketClientInfoEntry.getValue().getIsDbClient()==1){
                isInstruction();
                isAllIp(groups,socket);
                isDeleteSocket();
                specifiedSendSocketId(groups,socket);
            }
        }catch (Exception e){e.printStackTrace();}
    }


    private void isInstruction(){
        try {
            String data = new String(Userdata);
            if(!"".equals(data)){
                String permissions = utilsTools.textCenter(data,"<dbClient>","</dbClient>");
                String[]  clientGroup = utilsTools.textCenter(data, "<group>", "</group>").split(",");
                boolean bl = !"".equals(permissions) && clientGroup.length > 0;
                if(bl){
                    List<String> UserInfo = new ArrayList<>(Arrays.asList(clientGroup));
                    utilsTools.UserMaps.put(socketClientInfoEntry.getKey(),new clientInfo(UserInfo,Integer.parseInt(permissions)));
                    socketClientInfoEntry.getKey().getOutputStream().write(("您当前的权限等级为: " + permissions + " 您的客户端群组为: " + UserInfo).getBytes());
                    System.out.println("您当前的权限等级为: " + permissions + " 您的客户端群组为: " + UserInfo);
                }

            }
        }catch (Exception e){e.printStackTrace();}
    }

    //获取相同组的IP
    private void isAllIp(List<String> groups,Socket socket){
        try {
            String data = new String(Userdata);
            if(!"".equals(data)){
                String getIp = utilsTools.textCenter(data,"<get>","</get>");
                boolean bl = !"".equals(getIp) && "all".equals(getIp);
                if(bl){
                    for (String UserGroup:socketClientInfoEntry.getValue().getGroup()){
                        for(String oneTakeIpGroups :groups){
                            if(UserGroup.equals(oneTakeIpGroups)){
                                socketClientInfoEntry.getKey().getOutputStream().write((socket.getInetAddress().getHostAddress()+" | ").getBytes());
                            }
                        }
                    }
                }
            }
        }catch (Exception e){e.printStackTrace();}
    }


    //判断权限删除更改 只有1才允许使用
    // <up>IP地址</up><removes>group组名</removes><del>false</del>
    private void isDeleteSocket(){
        try {
            String data = new String(Userdata);
            if(!"".equals(data)){
                String updatePermissions = utilsTools.textCenter(data,"<up>","</up>");
                String updatePermissionsGroups = utilsTools.textCenter(data,"<removes>","</removes>");
                String updatePermissionsOffline = utilsTools.textCenter(data,"<del>","</del>");
                boolean bl = !"".equals(updatePermissions) && !"".equals(updatePermissionsGroups) && !"".equals(updatePermissionsOffline);
                if(bl){
                    Set<Map.Entry<Socket, clientInfo>> socketMap = utilsTools.UserMaps.entrySet();
                    for (Map.Entry<Socket,clientInfo> updateTakeIp:socketMap){
                        if(!socketClientInfoEntry.getKey().equals(updateTakeIp.getKey())){
                            for (String UserGroup:socketClientInfoEntry.getValue().getGroup()){
                                for (int i=0;i<updateTakeIp.getValue().getGroup().size();i++){
                                    if(UserGroup.equals(updateTakeIp.getValue().getGroup().get(i))){
                                        if(updateTakeIp.getKey().getInetAddress().getHostAddress().equals(updatePermissions)){
                                            if(UserGroup.equals(updatePermissionsGroups)){
                                                updateTakeIp.getValue().getGroup().set(i,UUID.randomUUID().toString());
                                                if(Boolean.parseBoolean(updatePermissionsOffline)){
                                                    updateTakeIp.getKey().getOutputStream().write(("对不起,你已被强制下线!操作组为: " + UserGroup).getBytes());
                                                    updateTakeIp.getKey().close();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){e.printStackTrace(); }
    }
    private void specifiedSendSocketId(List<String> groups,Socket socket){
        try {
            String data = new String(Userdata);
            if(!"".equals(data)){
                String sendAddress = utilsTools.textCenter(data,"<send>","</send>");
                String sendValues = utilsTools.textCenter(data,"<values>","</values>");
                boolean bl = !"".equals(sendAddress) && !"".equals(sendValues);
                if(bl){
                    for (String UserGroup:socketClientInfoEntry.getValue().getGroup()){
                        for(String oneTakeIpGroups :groups){
                            if(UserGroup.equals(oneTakeIpGroups)){
                                if(socket.getInetAddress().getHostAddress().equals(sendAddress)){
                                    socket.getOutputStream().write(sendValues.getBytes());
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){e.printStackTrace();}
    }
}
